package com.longnuoqi.mydoctor.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.longnuoqi.mydoctor.utils.ActivityCollection;
import com.longnuoqi.mydoctor.utils.EncodeDecodeUtil;
import com.yunhe.mydoctor.R;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Lenovo on 2015/12/29.
 */
public class UserRegistActivity extends AppCompatActivity {
    public static final String CLIENT_ID = "514570";
    public static final String CLIENT_SECRET = "c82919d597b3ce6a5490459ab181ded8";
    private Date birth;
    private String city;
    private String sign;
    private String phone;
    private ImageView back;

    private EditText account;
    private EditText mail;
    private EditText pwd;
    private EditText repwd;
    private String accountValue;
    private String mailValue;
    private String pwdValue;
    private String repwdValue;

    private ImageView agree;
    private TextView agreement;

    private RelativeLayout regist;

    private String url;

    private static boolean isExit = false;//判断是否退出
    private static boolean hasTask = false;//判断是否是任务
    private Timer timer = new Timer();//声明timer对象，计时器
    private TimerTask timerTask = new TimerTask() {//为timer安排一次执行或重复执行的任务
        @Override
        public void run() {
            isExit = false;
        }
    };

    /*双击退出程序*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!isExit) {
                isExit = true;
                Toast.makeText(UserRegistActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                if (!hasTask) {
                    timer.schedule(timerTask, 2000);//安排在指定延迟后执行指定的任务
                }
            } else {
                ActivityCollection.finishAll();
                //回收资源
                System.exit(0);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_regist_layout);
        ActivityCollection.addActivity(this);
        init();
    }

    private void init() {
        back = (ImageView) findViewById(R.id.user_regist_back_btn);

        account = (EditText) findViewById(R.id.user_regist_account_text);
        mail = (EditText) findViewById(R.id.user_regist_mail_text);
        pwd = (EditText) findViewById(R.id.user_regist_pwd_text);
        repwd = (EditText) findViewById(R.id.user_regist_repwd_text);

        agree = (ImageView) findViewById(R.id.user_regist_agree_btn);
        agreement = (TextView) findViewById(R.id.user_regist_agree_text);
        regist = (RelativeLayout) findViewById(R.id.user_regist_btn);

        back.setOnClickListener(onClickListener);
        agree.setOnClickListener(onClickListener);
        agreement.setOnClickListener(onClickListener);
        regist.setOnClickListener(onClickListener);

    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.user_regist_back_btn:
                    Intent intent = getIntent();
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
                case R.id.user_regist_agree_btn:
                    Toast.makeText(UserRegistActivity.this, "同意用户协议", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.user_regist_agree_text:
                    Toast.makeText(UserRegistActivity.this, "查看用户协议", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.user_regist_btn:
                    userRegist();
                    break;
                default:
                    break;
            }
        }
    };

    private void userRegist() {
        accountValue = account.getText().toString().trim();
        mailValue = mail.getText().toString().trim();
        pwdValue = pwd.getText().toString().trim();
        repwdValue = repwd.getText().toString().trim();
        if (!pwdValue.equals(repwdValue)) {
            Toast.makeText(UserRegistActivity.this, "两次密码输入不一致!", Toast.LENGTH_SHORT).show();
            pwd.setText("");
            repwd.setText("");
            pwd.requestFocus();
        } else if (pwdValue.length() < 3 || repwdValue.length() < 3) {
            Toast.makeText(UserRegistActivity.this, "密码长度过短!", Toast.LENGTH_SHORT).show();
            pwd.setText("");
            repwd.setText("");
            pwd.requestFocus();
        } else {
            try {
                accountValue = EncodeDecodeUtil.encoderUtf8(accountValue);
                birth = Date.valueOf("1950-01-01");
                city = EncodeDecodeUtil.encoderUtf8("北京");
                phone = "";
                sign = URLEncoder.encode("这个家伙很懒~", "utf-8");
                url = "http://www.tngou.net/api/oauth2/reg" + "?client_id=" + CLIENT_ID + "&client_secret=" +
                        CLIENT_SECRET + "&email=" + mailValue + "&account=" + accountValue + "&password=" +
                        pwdValue + "&birth=" + birth + "&city=" + city + "&signature=" + sign + "&phone=" + phone;
                Log.e("注册地址", url);
                RequestQueue requestQueue = Volley.newRequestQueue(this);
                StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        Log.e("注册返回数据==", s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            boolean status = jsonObject.getBoolean("status");
                            if (status) {
                                Intent intent = getIntent();
                                intent.putExtra("account", EncodeDecodeUtil.decoderUtf8(accountValue));
                                setResult(1, intent);
                                finish();
                            } else {
                                String message = jsonObject.getString("msg");
                                Toast.makeText(UserRegistActivity.this, message, Toast.LENGTH_SHORT).show();
                                account.setText("");
                                mail.setText("");
                                pwd.setText("");
                                repwd.setText("");
                                account.requestFocus();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("ErrorListener==", volleyError + "");

                    }
                });
                requestQueue.add(stringRequest);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollection.removeActivity(this);
    }
}
